//
//  Product_Detail_ViewController.m
//  chilemat
//
//  Created by Cristian Gonzalez Figueroa on 11-04-14.
//  Copyright (c) 2014 Chilemat SpA. All rights reserved.
//

#import "Product_Detail_iPad_ViewController.h"
#import "dao.h"
#import "classGenericCell.h"
#import "CustomCell.h"

@interface Product_Detail_iPad_ViewController ()

//@property (nonatomic, strong) NSArray *pageImages;

@property (nonatomic, strong) NSMutableArray *pageImages2;
@property (nonatomic, strong) NSMutableArray *pageViews;

- (void)loadVisiblePages;
- (void)loadPage:(NSInteger)page;
- (void)purgePage:(NSInteger)page;

@end

@implementation Product_Detail_iPad_ViewController

@synthesize objTextQty;
@synthesize viewSavingCart, objActivySavingCart;
@synthesize lblMarcProduct, lblDescriptionProduct, lblSKU, lblTotalReviews, lblPriceProduct, lblTotalShopingCart;
@synthesize imgStar1, imgStar2, imgStar3, imgStar4, imgStar5;
@synthesize lblOfferPriceProduct, viewLine;

@synthesize jsonProducto;
@synthesize imgProduct;
@synthesize btnAddToShoppingCart;
@synthesize imgDiscount;
@synthesize lblDiscount;

//-----------------------------------------
@synthesize scrollView = _scrollView;
@synthesize jsonImagesProduct;
@synthesize pageControl = _pageControl;
@synthesize viewFullImageProduct;
@synthesize imgFullImageProduct;
@synthesize btnCloseFullImageProduct;
@synthesize json;
@synthesize scrollViewFullImage;
@synthesize lblQty;

//--------------------------------------------------
//Observación: Tratamiento de las tallas y colores
@synthesize viewTallas;
@synthesize tableViewSearch;
@synthesize dataArraySearch = _dataArraySearch;
//--------------------------------------------------

int intNroImagesiPad = 0;

UIActivityIndicatorView *aiViewiPadImages;
//-----------------------------------------
static const CGFloat KEYBOARD_ANIMATION_DURATION = 0.3;
static const CGFloat PORTRAIT_KEYBOARD_HEIGHT = 300; //260;

NSTimer *timerSavingCartiPad;

int intPriceProductoiPad = 0; //Para grabar en el carro de compras
int intIdMarcaProductoiPad = 0;

int indexOfPageProductiPad = 0;

float floMinQtyProductiPad = 1;

float floMaxQtyProductiPad = 1;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    classGenericCell *objCell = [_dataArraySearch objectAtIndex:indexPath.row];
    
    NSString *strTitleLabel = @"";
    
    strTitleLabel = objCell.strTitleLabel; //Talla del producto, Color etc.
    
    NSLog(@"objCell.strIdProducto = %@", objCell.strIdProducto);
    
    //Almacenamos el registro en una tabla y enviamos a la página siguiente.
    NSLog(@"strTitleLabel = %@", strTitleLabel);
    
    viewTallas.hidden = YES;
    
    viewSavingCart.hidden = NO;
    
    dao *objDAO = [[dao alloc] init];
    NSString *strIdCurrentIDProducto = [NSString stringWithFormat:@"%i", [objDAO obtainCurrentProduct]] ;
    
    //*******
    //Como hay cambio de Id de imágen de producto, cambiamos el id de imagen de la foto en el disco del celular
    //--------------------------------------------------------------------------------------------------------
    //Leemos
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    
    //1.- Imagen normal
    NSString *strNameImageTmp = @"";
    NSString *documentsDirectory = [paths objectAtIndex:0];
    strNameImageTmp = [NSString stringWithFormat:@"strIdProducto_%@.jpg", strIdCurrentIDProducto];
    
    NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp ];
    UIImage* image = [UIImage imageWithContentsOfFile:path];
    //--------------------------------------------------------------------------------------------------------
    
    //Grabamos
    strNameImageTmp = [NSString stringWithFormat:@"3_%@.jpg", objCell.strIdProducto]; //Así la lee el carro después
    
    path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp];
    NSData* data = UIImageJPEGRepresentation(image, 1);
    [data writeToFile:path atomically:YES];
    //--------------------------------------------------------------------------------------------------------
    
    //*******
    
    [objDAO deleteCurrentProduct];
    [objDAO insertCurrentProduct:[objCell.strIdProducto intValue]];
    
    //Crear una variable de ambiente con el atributo (Talla)
    //*******************
    
    lblDescriptionProduct.text = objCell.strSubtitleLabel;
    
    lblPriceProduct.text = [self formatCurrencyValue:[ objCell.strPrice doubleValue]] ;
    intPriceProductoiPad = [objCell.strPrice intValue];
    
    timerSavingCartiPad = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(saveToShoppingCart:) userInfo:nil repeats:YES];
    
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [_dataArraySearch count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    CustomCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    
    if (cell == nil) {
        
        cell = [[CustomCell alloc] initWithStyle:UITableViewCellStyleDefault
                                 reuseIdentifier:CellIdentifier];
    }
    
    classGenericCell *objCell = [_dataArraySearch objectAtIndex:indexPath.row];
    
    cell.lblTitleLabel.text = objCell.strTitleLabel;
    cell.lblIdProducto.text = objCell.strIdProducto;
    
    return cell;
}

- (void) retrieveDataSearch{
    
    [_dataArraySearch removeAllObjects];
    _dataArraySearch = [[NSMutableArray alloc] init];
    
    self.tableViewSearch.hidden = NO;
    
    dao *objDAO = [[dao alloc] init];
    
    int intIdProducto = 0;
    
    intIdProducto = [objDAO obtainCurrentProduct];
    
    //intIdProducto = 786; //Prueba
    
    NSString * params;
    //------------------------------------------------------------------------------
    
    NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
    NSURLSession *defaultSession = [NSURLSession sessionWithConfiguration: defaultConfigObject delegate: nil delegateQueue: [NSOperationQueue mainQueue]];
    
    NSURL * url = [NSURL URLWithString:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonDetalleProducto.aspx"];
    NSMutableURLRequest * urlRequest = [NSMutableURLRequest requestWithURL:url];
    
    params =[NSString stringWithFormat:@"strJsonBase=JsonAtributosProducto&strIdProducto=%i", intIdProducto];
    
    [urlRequest setHTTPMethod:@"POST"];
    [urlRequest setHTTPBody:[params dataUsingEncoding:NSUTF8StringEncoding]];//NSNonLossyASCIIStringEncoding  NSUTF8StringEncoding
    
    NSURLSessionDataTask * dataTask =[defaultSession dataTaskWithRequest:urlRequest
                                                       completionHandler:^(NSData *data, NSURLResponse *response, NSError *error) {
                                                           NSLog(@"Response:%@ %@\n", response, error);
                                                           if(error == nil)
                                                           {
                                                               NSString * text = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
                                                               NSLog(@"Data = %@",text);
                                                               NSLog(@"Load Tallas perfecto!!!");
                                                               
                                                               NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
                                                               newStr = [self stringByRemovingControlCharacters:newStr];
                                                               
                                                               NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
                                                               
                                                               json = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
                                                               
                                                               //[{"idp":"478", "dp":"Botín de Seguridad Bicks Access.", "valorAtibuto":"38." }]
                                                               
                                                               for (int i = 0; i<json.count; i++)
                                                               {
                                                                   NSString *strIdProducto = [[json objectAtIndex:i] objectForKey:@"idp"];
                                                                   NSString *strDescripcionProducto = [[json objectAtIndex:i] objectForKey:@"dp"];
                                                                   NSString *strPrecioFinal = [[json objectAtIndex:i] objectForKey:@"precioFinal"];
                                                                   NSString *strTitleLabel = [[json objectAtIndex:i] objectForKey:@"valorAtibuto"];
                                                                   
                                                                   classGenericCell *objCell = [[classGenericCell alloc] initClassCell:strTitleLabel andSubtitleLabel:strDescripcionProducto andTrademark:@"" andIdMark:@"" andSKU:@"" andStrIdProducto:strIdProducto andReviews:@"" andstrPrice:strPrecioFinal andOfferPrice:@"" andstrPriceDuplicated:@"" andDiscount:@"" andOfferTime:@"" andQty:@""];
                                                                   
                                                                   [_dataArraySearch addObject:objCell];
                                                               }
                                                               
                                                               [self.tableViewSearch reloadData];
                                                               
                                                           }else{
                                                               NSLog(@"Error en load Tallas");
                                                           }
                                                       }];
    [dataTask resume];
    
}

-(UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    
    return imgFullImageProduct;
    
}

//----------------------------------------------------------------------------
-(void) cargarImages{
    
    NSInteger pageCount = self.pageImages2.count;
    
    // Set up the page control
    self.pageControl.currentPage = 0;
    self.pageControl.numberOfPages = pageCount;
    
    self.pageViews = [[NSMutableArray alloc] init];
    for (NSInteger i = 0; i < pageCount; ++i) {
        [self.pageViews addObject:[NSNull null]];
    }
    
    // Set up the content size of the scroll view
    CGSize pagesScrollViewSize = self.scrollView.frame.size;
    self.scrollView.contentSize = CGSizeMake(pagesScrollViewSize.width * self.pageImages2.count, pagesScrollViewSize.height);
    
    // Load the initial set of pages that are on screen
    [self loadVisiblePages];
    //----------------------------------------------------------------
}

-(void) imagesInformation{
    
    aiViewiPadImages = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
    aiViewiPadImages.hidesWhenStopped = YES; //I added this just so I could see it
    
    aiViewiPadImages.frame = CGRectMake(170, 140, 50, 50);
    
    [aiViewiPadImages startAnimating];
    
    [self.scrollView addSubview:aiViewiPadImages];
    
    //---------------------------
    self.pageImages2 = [[NSMutableArray alloc] init];
    
    dao *objDAO = [[dao alloc] init];
    int intIdProducto = 0;
    
    intIdProducto = [objDAO obtainCurrentProduct];
    
    //  NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonDetalleProducto.aspx?strJsonBase=JsonDetalleProducto&strIdProducto=%i", intIdProducto];
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonDetalleProducto.aspx?strJsonBase=obtenerJsonDetalleImagenes&strIdProducto=%i&strIdTipoImagen=1", intIdProducto];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil)
         {
             NSLog(@"Load imagenes perfecto!!!");
             
             NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             newStr = [self stringByRemovingControlCharacters:newStr];
             
             NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
             
             //[{"img":"7/277_2.jpg"}, {"img":"7/278_2.jpg"}, {"img":"7/279_2.jpg"}]
             //[{"idp":"7", "dp":"Alicate universal 8” 84023. ", "dcom":"Alicate universal 8” electricista 84023 negro. ", "sku":"120813 ", "nr":"0", "nv":"0", "pn":"1900", "po":"600", "dcto":"70", "tof":"29", "idm":"4", "dmp":"STANLEY ", "img":"7/277_2.jpg" }]
             
             jsonImagesProduct = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
             
             for (int i = 0; i<jsonImagesProduct.count; i++)
             {
                 NSString *strImage = [[jsonImagesProduct objectAtIndex:i] objectForKey:@"img"]; //[NSString stringWithFormat:@"3_%i.jpg", intIdProducto];
                 
                 strImage = [strImage stringByReplacingOccurrencesOfString: @ "/" withString: @ "_"];
                 
                 NSString *strUrlImgProducto = [NSString stringWithFormat:@"http://cdn.chilemat.com.s3-sa-east-1.amazonaws.com/ImagenProductos/%@", [[jsonImagesProduct objectAtIndex:i] objectForKey:@"img"]];
                 
                 NSURL *urlProducto = [NSURL URLWithString:strUrlImgProducto];
                 //-----------------------------------------------------------------------------------
                 //Leemos
                 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
                 
                 //1.- Imagen normal
                 //NSString *strNameImageTmp = @"";
                 NSString *documentsDirectory = [paths objectAtIndex:0];
                 //strNameImageTmp = [NSString stringWithFormat:@"3_%i.jpg", intIdProducto];
                 
                 NSString* path = [documentsDirectory stringByAppendingPathComponent:strImage];
                 UIImage* image = [UIImage imageWithContentsOfFile:path];
                 //-----------------------------------------------------------------------------------
                 
                 if (image == nil) {
                     
                     [self downloadImageWithURL:urlProducto completionBlock:^(BOOL succeeded, UIImage *image) {
                         if (succeeded) {
                             //---------------------------------------------------------------------------------------------------
                             NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                                  NSUserDomainMask, YES);
                             NSString *documentsDirectory = [paths objectAtIndex:0];
                             
                             NSString *strNameImageTmp = [NSString stringWithFormat:@"%@", strImage];
                             
                             NSLog(@"strImage=%@", strImage);
                             
                             NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp];
                             NSData* data = UIImageJPEGRepresentation(image, 1);
                             [data writeToFile:path atomically:YES];
                             
                             intNroImagesiPad = intNroImagesiPad + 1;
                             
                             [self.pageImages2 addObject:strImage];
                             
                             if (intNroImagesiPad == jsonImagesProduct.count) { //Asíncronamente se cargaron los banner al inicio
                                 [self cargarImages];
                                 [aiViewiPadImages stopAnimating];
                             }
                             //---------------------------------------------------------------------------------------------------
                         }
                     }];
                 }else{
                     intNroImagesiPad = intNroImagesiPad + 1;
                     
                     [self.pageImages2 addObject:strImage];
                     
                     if (intNroImagesiPad == jsonImagesProduct.count) { //Asíncronamente se cargaron los banner al inicio
                         [self cargarImages];
                         [aiViewiPadImages stopAnimating];
                     }
                     
                 }//if (image == nil)
                 
             }//for (int i = 0
             
         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing was downloaded.");
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
         }
     }];
    
}


- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, UIImage *image))completionBlock
{
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    [NSURLConnection sendAsynchronousRequest:request
                                       queue:[NSOperationQueue mainQueue]
                           completionHandler:^(NSURLResponse *response, NSData *data, NSError *error) {
                               if ( !error )
                               {
                                   UIImage *image = [[UIImage alloc] initWithData:data];
                                   completionBlock(YES,image);
                               } else{
                                   completionBlock(NO,nil);
                               }
                           }];
}

- (void)loadPage:(NSInteger)page {
    
    if (page < 0 || page >= self.pageImages2.count) {
        // If it's outside the range of what we have to display, then do nothing
        return;
    }
    
    // Load an individual page, first checking if you've already loaded it
    UIView *pageView = [self.pageViews objectAtIndex:page];
    if ((NSNull*)pageView == [NSNull null]) {
        CGRect frame = self.scrollView.bounds;
        frame.origin.x = frame.size.width * page;
        frame.origin.y = 0.0f;
        
        NSString *strNameImage = @"";
        strNameImage = [self.pageImages2 objectAtIndex:page];
        //-----------------------------------------------------------------------------------
        //Leemos
        NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
        
        NSString *strNameImageTmp = @"";
        NSString *documentsDirectory = [paths objectAtIndex:0];
        strNameImageTmp = [NSString stringWithFormat:@"%@", strNameImage];
        
        NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp ];
        UIImage* imgBanner = [UIImage imageWithContentsOfFile:path];
        //-----------------------------------------------------------------------------------
        
        UIImageView *newPageView = [[UIImageView alloc] initWithImage:imgBanner];
        //      newPageView.contentMode = UIViewContentModeScaleAspectFit;
        newPageView.frame = frame;
        [self.scrollView addSubview:newPageView];
        [self.pageViews replaceObjectAtIndex:page withObject:newPageView];
    }
    
}

- (void)purgePage:(NSInteger)page {
    if (page < 0 || page >= self.pageImages2.count) {
        // If it's outside the range of what you have to display, then do nothing
        return;
    }
    
    // Remove a page from the scroll view and reset the container array
    UIView *pageView = [self.pageViews objectAtIndex:page];
    if ((NSNull*)pageView != [NSNull null]) {
        [pageView removeFromSuperview];
        [self.pageViews replaceObjectAtIndex:page withObject:[NSNull null]];
    }
}

- (void)loadVisiblePages {
    // First, determine which page is currently visible
    CGFloat pageWidth = self.scrollView.frame.size.width;
    NSInteger page = (NSInteger)floor((self.scrollView.contentOffset.x * 2.0f + pageWidth) / (pageWidth * 2.0f));

    // Update the page control
    self.pageControl.currentPage = page;
    
    // Work out which pages you want to load
    NSInteger firstPage = page - 1;
    NSInteger lastPage = self.pageImages2.count -1 ; //page + 1;
    
    // Purge anything before the first page
    for (NSInteger i=0; i<firstPage; i++) {
        //      [self purgePage:i];
    }
    for (NSInteger i=firstPage; i<=lastPage; i++) {
        [self loadPage:i];
    }
    for (NSInteger i=lastPage+1; i<self.pageImages2.count; i++) {
        //      [self purgePage:i];
    }
}


- (void)hideTabBar {
    UITabBar *tabBar = self.tabBarController.tabBar;
    UIView *parent = tabBar.superview; // UILayoutContainerView
    UIView *content = [parent.subviews objectAtIndex:0];  // UITransitionView
    UIView *window = parent.superview;
    
    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect tabFrame = tabBar.frame;
                         tabFrame.origin.y = CGRectGetMaxY(window.bounds);
                         tabBar.frame = tabFrame;
                         content.frame = window.bounds;
                     }];
}

- (void)showTabBar {
    UITabBar *tabBar = self.tabBarController.tabBar;
    UIView *parent = tabBar.superview; // UILayoutContainerView
    UIView *content = [parent.subviews objectAtIndex:0];  // UITransitionView
    UIView *window = parent.superview;
    
    [UIView animateWithDuration:0.5
                     animations:^{
                         CGRect tabFrame = tabBar.frame;
                         tabFrame.origin.y = CGRectGetMaxY(window.bounds) - CGRectGetHeight(tabBar.frame);
                         tabBar.frame = tabFrame;
                         
                         CGRect contentFrame = content.frame;
                         contentFrame.size.height -= tabFrame.size.height;
                     }];
}

-(void) loadStars: (int) intTotalReviews{
    
    if (intTotalReviews == 0) {
        imgStar1.image = [UIImage imageNamed:@"star_off.png"];
        imgStar2.image = [UIImage imageNamed:@"star_off.png"];
        imgStar3.image = [UIImage imageNamed:@"star_off.png"];
        imgStar4.image = [UIImage imageNamed:@"star_off.png"];
        imgStar5.image = [UIImage imageNamed:@"star_off.png"];
    }
    
    if (intTotalReviews == 1) {
        imgStar1.image = [UIImage imageNamed:@"star_on.png"];
        imgStar2.image = [UIImage imageNamed:@"star_off.png"];
        imgStar3.image = [UIImage imageNamed:@"star_off.png"];
        imgStar4.image = [UIImage imageNamed:@"star_off.png"];
        imgStar5.image = [UIImage imageNamed:@"star_off.png"];
    }
    
    if (intTotalReviews == 2) {
        imgStar1.image = [UIImage imageNamed:@"star_on.png"];
        imgStar2.image = [UIImage imageNamed:@"star_on.png"];
        imgStar3.image = [UIImage imageNamed:@"star_off.png"];
        imgStar4.image = [UIImage imageNamed:@"star_off.png"];
        imgStar5.image = [UIImage imageNamed:@"star_off.png"];
    }
    
    if (intTotalReviews == 3) {
        imgStar1.image = [UIImage imageNamed:@"star_on.png"];
        imgStar2.image = [UIImage imageNamed:@"star_on.png"];
        imgStar3.image = [UIImage imageNamed:@"star_on.png"];
        imgStar4.image = [UIImage imageNamed:@"star_off.png"];
        imgStar5.image = [UIImage imageNamed:@"star_off.png"];
    }
    
    if (intTotalReviews == 4) {
        imgStar1.image = [UIImage imageNamed:@"star_on.png"];
        imgStar2.image = [UIImage imageNamed:@"star_on.png"];
        imgStar3.image = [UIImage imageNamed:@"star_on.png"];
        imgStar4.image = [UIImage imageNamed:@"star_on.png"];
        imgStar5.image = [UIImage imageNamed:@"star_off.png"];
    }
    
    if (intTotalReviews >= 5) {
        imgStar1.image = [UIImage imageNamed:@"star_on.png"];
        imgStar2.image = [UIImage imageNamed:@"star_on.png"];
        imgStar3.image = [UIImage imageNamed:@"star_on.png"];
        imgStar4.image = [UIImage imageNamed:@"star_on.png"];
        imgStar5.image = [UIImage imageNamed:@"star_on.png"];
    }
    
}

-(NSString*) formatCurrencyValue:(double)value
{
    NSNumberFormatter *numberFormatter = [[NSNumberFormatter alloc] init];
    [numberFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
    [numberFormatter setCurrencySymbol:@"$"];
    [numberFormatter setNumberStyle:NSNumberFormatterCurrencyStyle];
    NSNumber *c = [NSNumber numberWithFloat:value];
    return [numberFormatter stringFromNumber:c];
}

- (NSString *)stringByRemovingControlCharacters: (NSString *)inputString
{
    NSCharacterSet *controlChars = [NSCharacterSet controlCharacterSet];
    NSRange range = [inputString rangeOfCharacterFromSet:controlChars];
    if (range.location != NSNotFound) {
        NSMutableString *mutable = [NSMutableString stringWithString:inputString];
        while (range.location != NSNotFound) {
            [mutable deleteCharactersInRange:range];
            range = [mutable rangeOfCharacterFromSet:controlChars];
        }
        return mutable;
    }
    return inputString;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    self.scrollView.delegate = self;

    //---------------------------------------------------------------------------------
    //Tallas de un producto
    self.tableViewSearch.delegate = self;
    self.tableViewSearch.dataSource = self;
    
    //Cargamos las tallas si es que existen
    [self retrieveDataSearch];
    
    //---------------------------------------------------------------------------------
    indexOfPageProductiPad = 0;

    floMinQtyProductiPad = 1;
    floMaxQtyProductiPad = 1;
    
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCaptured:)];
    [self.scrollView addGestureRecognizer:singleTap];

    UITapGestureRecognizer *singleTapImgFullProduct = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(singleTapGestureCapturedClose:)];
    [self.viewFullImageProduct addGestureRecognizer:singleTapImgFullProduct];
    //-------------------------------------------------------
    
    [self hideTabBar];
    
    dao *objDAO = [[dao alloc] init];
    int intIdProducto = 0;
    
    intIdProducto = [objDAO obtainCurrentProduct];
    
    NSLog(@"intIdProducto =%i", intIdProducto);

    //----------------------------------------------------------------------------------
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonDetalleProducto.aspx?strJsonBase=JsonDetalleProducto&strIdProducto=%i", intIdProducto];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil)
         {
             NSLog(@"Load producto perfecto!!!");
             
             NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             newStr = [self stringByRemovingControlCharacters:newStr];
             
             NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
             
             //[{"idp":"7", "dp":"Alicate universal 8” 84023. ", "dcom":"Alicate universal 8” electricista 84023 negro. ", "sku":"120813 ", "nr":"0", "nv":"0", "pn":"1900", "po":"600", "dcto":"70", "tof":"0", "idm":"4", "dmp":"Stanley", "img":"7/276_1.jpg", "min":"1", "max":"20" }]
             
             jsonProducto = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
             
             for (int i = 0; i<jsonProducto.count; i++)
             {
                 lblMarcProduct.text = [[jsonProducto objectAtIndex:i] objectForKey:@"dmp"];
                 //lblDescriptionProduct.text = [[jsonProducto objectAtIndex:i] objectForKey:@"dcom"];
                 lblDescriptionProduct.text = [[jsonProducto objectAtIndex:i] objectForKey:@"dp"];
                 lblSKU.text = [[jsonProducto objectAtIndex:i] objectForKey:@"sku"];
                 lblTotalReviews.text = [NSString stringWithFormat:@"(%@)", [[jsonProducto objectAtIndex:i] objectForKey:@"nr"]];
                 lblPriceProduct.text = [NSString stringWithFormat:@"%@",  [self formatCurrencyValue:[[[jsonProducto objectAtIndex:i] objectForKey:@"po"] doubleValue]]  ];
                 
                 floMinQtyProductiPad = [ [[jsonProducto objectAtIndex:i] objectForKey:@"min"] floatValue];
                 floMaxQtyProductiPad = [ [[jsonProducto objectAtIndex:i] objectForKey:@"max"] floatValue];
                 
                 int intIdMarca = [ [[jsonProducto objectAtIndex:i] objectForKey:@"idm"] intValue];
                 NSString *strMarcaProducto = [[jsonProducto objectAtIndex:i] objectForKey:@"dmp"];
                 
                 //Actualizamos la marca caso a caso para hacer mas en paralelo y si no existe la creamos para utilizarla en la consulta del carro y posteriores
                 [objDAO deleteMarcaProducto:intIdMarca];
                 [objDAO insertMarcaProducto:intIdMarca strDescripcionMarca:strMarcaProducto];
                 
                 NSString *strDiscount = @"%";
                 NSString *strDiscountValue = [[jsonProducto objectAtIndex:i] objectForKey:@"dcto"];
                 lblDiscount.text = [NSString stringWithFormat:@"-%@ %@", [[jsonProducto objectAtIndex:i] objectForKey:@"dcto"], strDiscount];
                 
                 if (![strDiscountValue  isEqual: @"0"]) {
                     imgDiscount.hidden = NO;
                     lblDiscount.hidden = NO;
                 }
                 
                 lblQty.text = [[jsonProducto objectAtIndex:i] objectForKey:@"unidad"];
                 
                 //Observación: Variables para grabar en el carro de compra
                 //-----------------------------------------------------------
                 intPriceProductoiPad = [ [[jsonProducto objectAtIndex:i] objectForKey:@"po"] intValue];
                 intIdMarcaProductoiPad = [ [[jsonProducto objectAtIndex:i] objectForKey:@"idm"] intValue];
                 //-----------------------------------------------------------
                 
 //              int intOfferPrice = [ [[jsonProducto objectAtIndex:i] objectForKey:@"po"] intValue];
                 
                 if (![strDiscountValue  isEqual: @"0"]) {
                     lblOfferPriceProduct.text = [NSString stringWithFormat:@"Antes: %@",  [self formatCurrencyValue:[[[jsonProducto objectAtIndex:i] objectForKey:@"pn"] doubleValue]]  ];
                     lblOfferPriceProduct.hidden = NO;
                     viewLine.hidden = NO;
                 }else{
                     
                     lblOfferPriceProduct.hidden = YES;
                     viewLine.hidden = YES;
                 }
/*
                 if (intOfferPrice > 0 ) { //Si viene una oferta la mostramos
                     
                     lblOfferPriceProduct.text = [NSString stringWithFormat:@"Antes: %@",  [self formatCurrencyValue:[[[jsonProducto objectAtIndex:i] objectForKey:@"pn"] doubleValue]]  ];
                     lblOfferPriceProduct.hidden = NO;
                     viewLine.hidden = NO;
                 }else{
                     
                     lblOfferPriceProduct.hidden = YES;
                     viewLine.hidden = YES;
                 }
*/
                 
                 [self totalShopingCart];
                 
                 int intTotalReviews = [[[jsonProducto objectAtIndex:i] objectForKey:@"nr"] intValue];
                 
                 [self loadStars:intTotalReviews];

                 NSString *strImage = [NSString stringWithFormat:@"3_%@.jpg", [[jsonProducto objectAtIndex:i] objectForKey:@"idp"]];
                 NSString *strUrlImgProducto = [NSString stringWithFormat:@"http://cdn.chilemat.com.s3-sa-east-1.amazonaws.com/ImagenProductos/%@", [[jsonProducto objectAtIndex:i] objectForKey:@"img"]];
                 
                 NSURL *urlProducto = [NSURL URLWithString:strUrlImgProducto];
                 
                 //-----------------------------------------------------------------------------------
                 //Leemos
                 NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
                 
                 //1.- Imagen normal
                 NSString *strNameImageTmp = @"";
                 NSString *documentsDirectory = [paths objectAtIndex:0];
                 strNameImageTmp = [NSString stringWithFormat:@"3_%@.jpg", [[jsonProducto objectAtIndex:i] objectForKey:@"idp"]];
                 
                 NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp ];
                 UIImage* image = [UIImage imageWithContentsOfFile:path];
                 //-----------------------------------------------------------------------------------
                 
                 if (image == nil) { //Si la imágen estaba grabada en el disco la puedo rescatar y la bajo por actualización
                     
                     [self downloadImageWithURL:urlProducto completionBlock:^(BOOL succeeded, UIImage *image) {
                         if (succeeded) {
                             
                             //---------------------------------------------------------------------------------------------------
                             NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                                  NSUserDomainMask, YES);
                             NSString *documentsDirectory = [paths objectAtIndex:0];
                             
                             NSString *strNameImageTmp = [NSString stringWithFormat:@"%@", strImage];
                             
                             NSLog(@"strImage=%@", strImage);
                             
                             NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp];
                             NSData* data = UIImageJPEGRepresentation(image, 1);
                             [data writeToFile:path atomically:YES];
                             
                             [imgProduct setImage:image]; //Asignamos la imagen
                             
                             //---------------------------------------------------------------------------------------------------
                         }
                     }];
                 }else{
                     [imgProduct setImage:image]; //Asignamos la imagen
                     
                     [self downloadImageWithURL:urlProducto completionBlock:^(BOOL succeeded, UIImage *image) {
                         if (succeeded) {
                             
                             //---------------------------------------------------------------------------------------------------
                             NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
                                                                                  NSUserDomainMask, YES);
                             NSString *documentsDirectory = [paths objectAtIndex:0];
                             
                             NSString *strNameImageTmp = [NSString stringWithFormat:@"%@", strImage];
                             
                             NSLog(@"strImage=%@", strImage);
                             
                             NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp];
                             NSData* data = UIImageJPEGRepresentation(image, 1);
                             [data writeToFile:path atomically:YES];
                             //---------------------------------------------------------------------------------------------------
                         }
                     }];
                 }

                 [btnAddToShoppingCart setEnabled:YES];
             }
             
         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing was downloaded.");
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
         }
     }];
    
//Cargamos el scrool de imágenes
    
    intNroImagesiPad = 0;
    
    [self imagesInformation];
    
}

-(void) totalShopingCart{
    
    //-------------------------------------------------------------------------------------
    NSArray *ArrayResumeShoppingCart;
    dao *objDAO = [[dao alloc] init];
    int intIdUsuario = 0;
    
    intIdUsuario = [objDAO obtainCurrentIdUser];
    
    if (intIdUsuario == -1) {
        intIdUsuario = 1;
    }
    
    ArrayResumeShoppingCart = [objDAO obtainResumeShoppingCart:intIdUsuario];
    
    if (ArrayResumeShoppingCart.count > 0) {
        
        NSLog(@"strTotal =%i", [ArrayResumeShoppingCart[0] intValue] );
        NSLog(@"strCantidadTotal =%i", [ArrayResumeShoppingCart[1] intValue] );
        
        lblTotalShopingCart.text = ArrayResumeShoppingCart[1];
    }
    //-------------------------------------------------------------------------------------
    
}

-(void)cancelNumberPad{
    
    //-----------------------------------------------------
    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += PORTRAIT_KEYBOARD_HEIGHT; //animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];
    //-----------------------------------------------------
    
    [self.view endEditing:YES];
}

- (void)doneWithNumberPad:(id)sender {
    
    //-----------------------------------------------------

    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y += PORTRAIT_KEYBOARD_HEIGHT; //animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];

    [self.view endEditing:YES];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    // Load the pages which are now on screen
    [self loadVisiblePages];
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    indexOfPageProductiPad = scrollView.contentOffset.x / scrollView.frame.size.width;
    
    NSLog(@"indexOfPage =%i", indexOfPageProductiPad);
}

- (void)singleTapGestureCapturedClose:(UITapGestureRecognizer *)gesture
{
    //  CGPoint touchPoint=[gesture locationInView:self.scrollView];
    
    //1.- Detectamos un evento en el scrollview de la imagen
    NSLog(@"Close ImageView");
    
    viewFullImageProduct.hidden = YES;
    
    //-----------------------------------------------------------------------------------
}

- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture
{
    //  CGPoint touchPoint=[gesture locationInView:self.scrollView];
    
    //1.- Detectamos un evento en el scrollview de la imagen
    NSLog(@"Tap ScrollView");
    
    NSString *strNameImage = @"";
    strNameImage = [self.pageImages2 objectAtIndex:indexOfPageProductiPad];
    //-----------------------------------------------------------------------------------
    //Leemos
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask, YES);
    
    NSString *strNameImageTmp = @"";
    NSString *documentsDirectory = [paths objectAtIndex:0];
    strNameImageTmp = [NSString stringWithFormat:@"%@", strNameImage];
    
    NSString* path = [documentsDirectory stringByAppendingPathComponent:strNameImageTmp ];
    UIImage* imgFullProduct = [UIImage imageWithContentsOfFile:path];
    
    [imgFullImageProduct setImage:imgFullProduct];

    imgFullImageProduct.contentMode  = UIViewContentModeScaleAspectFit; //UIViewContentModeScaleToFill;
//  imgFullImageProduct.contentMode  = UIViewContentModeScaleToFill;
    
    [scrollViewFullImage addSubview:imgFullImageProduct];
    
    scrollViewFullImage.maximumZoomScale = 3.0;
    scrollViewFullImage.minimumZoomScale = 1;
    
    scrollViewFullImage.userInteractionEnabled = YES;
    scrollViewFullImage.delegate = self;
    
    viewFullImageProduct.hidden = NO;
    
    //-----------------------------------------------------------------------------------
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
}

- (void)viewDidUnload {
    [super viewDidUnload];
    // Release any retained subviews of the main view. // e.g. self.myOutlet = nil;
    
    [timerSavingCartiPad invalidate];
    timerSavingCartiPad = nil;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
 {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
 }

*/

- (IBAction)closeFullImageProduct:(id)sender {
    
    viewFullImageProduct.hidden = YES;
}

- (IBAction)backToHome:(id)sender {
    
    if (viewTallas.hidden == YES) {
        
        [self showTabBar];
        
        dao *objDAO = [[dao alloc] init];
        
        int intProductBack = [objDAO obtainProductBack];
        
        NSLog(@"intProductBack =%i", intProductBack);
        
        if (intProductBack == 0) {
            //Back desde el home
            [self.navigationController popToRootViewControllerAnimated:YES];
            
        }else if (intProductBack == 2) //Back desde Categorias
            
            [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:2] animated:YES];
        
        else{
            //Back desde la busqueda
            [self.navigationController popToViewController:[self.navigationController.viewControllers objectAtIndex:1] animated:YES];
        }
        
    }else{
        //Simulamos un volver ocultando la vista de tallas emergente
        viewTallas.hidden = YES;
    }
    
}
- (IBAction)addQty:(id)sender {
    
    NSInteger intTxtCantidad = 0;
    
    intTxtCantidad = [objTextQty.text integerValue] + 1;
    
    objTextQty.text = [NSString stringWithFormat:@"%li", (long) intTxtCantidad];
}

- (IBAction)decreaceQty:(id)sender {
    
    NSInteger intTxtCantidad = 0;
    
    intTxtCantidad = [objTextQty.text integerValue] - 1;
    
    if (intTxtCantidad < 0) {
        intTxtCantidad = 0;
    }
    
    objTextQty.text = [NSString stringWithFormat:@"%li", (long)intTxtCantidad];
}

- (IBAction)addToShoppingCart:(id)sender {
    
    NSInteger intExistAttributos = _dataArraySearch.count;
    
    if (intExistAttributos > 0 ) {
        
        viewTallas.hidden = NO;
    }else{
        
        viewSavingCart.hidden = NO;
        
        timerSavingCartiPad = [NSTimer scheduledTimerWithTimeInterval:0.5 target:self selector:@selector(saveToShoppingCart:) userInfo:nil repeats:YES];
    }
}

-(int) insUpdShoppingCartCloud: (int) intIdUsuario floQty:(float) floCantidad intIdProducto:(int) intIdProducto{
    
    //Create or Product Shopping Cart
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonCarroCompra.aspx?strJsonBase=JsonInsUpd&strIdUsuario=%i&strIdProducto=%i&strCantidad=%.2f", intIdUsuario, intIdProducto, floCantidad];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    NSURLResponse * response = nil;
    NSError * error = nil;
    NSData * data = [NSURLConnection sendSynchronousRequest:urlRequest
                                          returningResponse:&response
                                                      error:&error];
    if (error == nil)
    {
        json = [NSJSONSerialization JSONObjectWithData:data options:kNilOptions error:nil];

        int intIdResumenCarroCompra = 0;
        
        intIdResumenCarroCompra = [ [[json objectAtIndex:0] objectForKey:@"intIdResumenCarroCompra"] intValue];
        
        return intIdResumenCarroCompra;
    }else{
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @""
                                                       message: @"Un error al grabar el carro a ocurrido, intente nuevamente."
                                                      delegate: self
                                             cancelButtonTitle:@"Seguir comprando"
                                             otherButtonTitles:@"Ir al carrito",nil];
        [alert show];
        
        NSLog(@"Error");
        return 0;
    }
    
}

-(void) crearUsrCloud{
    
    NSString *strUrl = [NSString stringWithFormat:@"http://mobileecommerce.elasticbeanstalk.com/MobileJsonRegistraUsuario.aspx?strJsonBase=JsonUsuarioIns"];
    
    NSURL *url = [NSURL URLWithString:strUrl];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    
    [NSURLConnection
     sendAsynchronousRequest:urlRequest
     queue:[NSOperationQueue mainQueue]
     completionHandler:^(NSURLResponse *response,
                         NSData *data,
                         NSError *error)
     {
         if ([data length] >0 && error == nil)
         {
             NSLog(@"Crear Usuario perfecto");
             
             NSString* newStr = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
             newStr = [self stringByRemovingControlCharacters:newStr];
             
             NSData* dataUTF8 = [newStr dataUsingEncoding:NSUTF8StringEncoding];
             
             //[{"usr":"21"}]
             
             json = [NSJSONSerialization JSONObjectWithData:dataUTF8 options:NSJSONReadingMutableLeaves error:nil];
             
             int intIdUsuario = [  [[json objectAtIndex:0] objectForKey:@"usr"] intValue];
             
             NSLog(@"intIdUsuario =%i", intIdUsuario);
             
             dao *objDAO = [[dao alloc] init];
             
             [objDAO deleteCurrentIdUser];
             [objDAO insertCurrentIdUser:intIdUsuario];
             
             //strSocialLoginId = 3 //Correo
             [objDAO deleteUserSistem:intIdUsuario];
             
             int intRetorno = [objDAO insertUserSistem:intIdUsuario strUser:@"" strPassword:@"" strSocialLoginId:@"3" strEmail:@""];
             
             NSLog(@"intRetorno =%i", intRetorno);
             
             
         }
         else if ([data length] == 0 && error == nil)
         {
             NSLog(@"Nothing was downloaded.");
         }
         else if (error != nil){
             NSLog(@"Error = %@", error);
         }
     }];
    
}

- (void) saveToShoppingCart:(NSTimer *) timer {
    
    //Detenemos el timer
    [timerSavingCartiPad invalidate];
    timerSavingCartiPad = nil;
    viewSavingCart.hidden = YES;
    
    dao *objDAO = [[dao alloc] init];
    int intIdProducto = [objDAO obtainCurrentProduct];
    int intIdUsuario = 0;
    
    intIdUsuario = [objDAO obtainCurrentIdUser];

    if (intIdUsuario <= 1) { //No existe o se creó el usuario 1 por defecto
        
        [self crearUsrCloud];
        
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @""
                                                       message: @"Un error interno a ocurrido, intente nuevamente."
                                                      delegate: self
                                             cancelButtonTitle:@"Seguir comprando"
                                             otherButtonTitles:@"Ir al carrito",nil];
        [alert show];
        
    }else{
        
        NSString *strSKU, *strDescProd, *strQty;
        int intIdMarca = 0;
        float dblCantidad = 0;
        int intNeto, intIva, intTotal, intReturn;

        strQty = lblQty.text;
        strSKU = lblSKU.text;                           //ArrayProduct[4];
        strDescProd = lblDescriptionProduct.text;       //ArrayProduct[1];
        intIdMarca = intIdMarcaProductoiPad;            //[ArrayProduct[11] intValue];
        dblCantidad = [objTextQty.text floatValue];
        intNeto = 0;
        intIva = 0;
        intTotal = intPriceProductoiPad;              //[ArrayProduct[7] intValue];

        //****Parche temporal para mostrar este dato que parece mas mas importante en el contexto
        strSKU = strQty;
        
        if ((dblCantidad >= floMinQtyProductiPad) && (dblCantidad <= floMaxQtyProductiPad)) {

            int intIdResumenCarroCompra = [self insUpdShoppingCartCloud:intIdUsuario floQty:dblCantidad intIdProducto:intIdProducto];;
            
            if (intIdResumenCarroCompra > 0) {
                //***************************************************************************
                int intExistProductoShoppingCart = 0;
                
                intExistProductoShoppingCart = [objDAO obtainExistProductShoppingCart:intIdUsuario intIdProducto:intIdProducto];
                
                if (intExistProductoShoppingCart > 0) {
                    
                    [objDAO deleteProductShoppingCart:intIdUsuario intIdProducto:intIdProducto];
                    
                    intReturn = [objDAO insertProductShoppingCart:intIdUsuario intIdCarro:intIdResumenCarroCompra intIdProducto:intIdProducto strSKU:strSKU strDescProd:strDescProd intIdMarca:intIdMarca dblCantidad:dblCantidad intNeto:intNeto intIva:intIva intTotal:intTotal];
                    
                }else{
                    intReturn = [objDAO insertProductShoppingCart:intIdUsuario intIdCarro:intIdResumenCarroCompra intIdProducto:intIdProducto strSKU:strSKU strDescProd:strDescProd intIdMarca:intIdMarca dblCantidad:dblCantidad intNeto:intNeto intIva:intIva intTotal:intTotal];
                }
                
                if (intReturn == 1) { //Exito
                    
                    NSArray *ArrayResumeShoppingCart;
                    
                    ArrayResumeShoppingCart = [objDAO obtainResumeShoppingCart:intIdUsuario];
                    
                    if (ArrayResumeShoppingCart.count > 0) {
                        
                        NSLog(@"strTotal =%i", [ArrayResumeShoppingCart[0] intValue] );
                        NSLog(@"strCantidadTotal =%i", [ArrayResumeShoppingCart[1] intValue] );
                        
                        lblTotalShopingCart.text = ArrayResumeShoppingCart[1];
                    }
                    
                    UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @""
                                                                   message: @"Producto agregado al carro."
                                                                  delegate: self
                                                         cancelButtonTitle:@"Seguir comprando"
                                                         otherButtonTitles:@"Ir al carrito",nil];
                    [alert show];
                }
                //***************************************************************************
            }else{ //Grabado en el cloud
                UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@""
                                                                message:@"Error remoto al agregar el producto al carro, intente nuevamente."
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
                [alert show];
            }
            
        }//Rango de cantidades mínimas y máximas
        else{
            NSString *strMensaje = [NSString stringWithFormat:@"La cantidad debe estar entre %2.f y %2.f", floMinQtyProductiPad, floMaxQtyProductiPad];
            
            UIAlertView *alert = [[UIAlertView alloc]initWithTitle: @""
                                                           message: strMensaje
                                                          delegate: self
                                                 cancelButtonTitle:@"Seguir comprando"
                                                 otherButtonTitles:@"Ir al carrito",nil];
            [alert show];
            
        }
    }
    
    
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) //Seguir comprando
    {
        NSLog(@"Seguir comprando...");
        
    }else{ //Ir al carro
        //Liberamos el retorno al home por cambio de storyboard
        NSUserDefaults *prefs = [NSUserDefaults standardUserDefaults];
        [prefs setObject:@"LoadHomeFirst" forKey:@"keyToLookupString"];
        
        UIStoryboard *mainStoryBoard = [UIStoryboard storyboardWithName:@"Main_iPad" bundle:nil];
        UITabBarController *tab = [mainStoryBoard instantiateViewControllerWithIdentifier:@"TabBarView"];
        [tab setSelectedIndex:2];
        
        [self presentViewController:tab animated:YES completion:nil];
    }
}

- (IBAction)changeQty:(id)sender {
    
    //----------------------------------------

    CGRect viewFrame = self.view.frame;
    viewFrame.origin.y -= PORTRAIT_KEYBOARD_HEIGHT; //animatedDistance;
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationBeginsFromCurrentState:YES];
    [UIView setAnimationDuration:KEYBOARD_ANIMATION_DURATION];
    
    [self.view setFrame:viewFrame];
    
    [UIView commitAnimations];

    //----------------------------------------
    
    UIToolbar* numberToolbar = [[UIToolbar alloc]initWithFrame:CGRectMake(0, 0, 320, 50)];
    numberToolbar.barStyle = UIBarStyleDefault;
    
    numberToolbar.items = [NSArray arrayWithObjects:
                           [[UIBarButtonItem alloc]initWithTitle:@"" style:UIBarButtonItemStylePlain target:self action:@selector(cancelNumberPad) ],
                           [[UIBarButtonItem alloc]initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil],
                           [[UIBarButtonItem alloc]initWithTitle:@"Ok" style:UIBarButtonItemStyleDone target:self action:@selector(doneWithNumberPad:)],
                           nil];
    
    [numberToolbar sizeToFit];
    
    objTextQty.inputAccessoryView = numberToolbar;
}

- (IBAction)updateQty:(id)sender {
    
    NSLog(@"Update Qty.........");
    
}



@end
